var express = require('express');
var router = express.Router();
const {brandModel, catgoryModel, goodsModel, orderModel} = require('../model/model')
const multiparty = require('multiparty')
const fs = require('fs');
const { default: mongoose } = require('mongoose');
const { query } = require('express');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});




// 品牌模块功能

// 展示品牌列表  下方判断分页和不分页, 添加商品可用
router.get('/brand', async (req, res) => {
  let query = req.query
  let page = parseInt(query.page)
  let pagesize = parseInt(query.pagesize)
  let data = ''
  let total = 0
  if (page && pagesize){
    data = await brandModel.find({is_del: 1}).limit(pagesize).skip((page-1)*pagesize).exec()
    let arr = await brandModel.find({is_del:1}).exec()
    total = arr.length
  }else{
    data = await brandModel.find({is_del:1}).exec()
  }
  
  res.send({
    data, total
  })
})

// 展示品牌回收站列表
router.get('/brandbin', async (req, res) => {
  let query = req.query
  let page = parseInt(query.page) || 1
  let pagesize = parseInt(query.pagesize) || 2
  let data = await brandModel.find({is_del: 0}).limit(pagesize).skip((page-1)*pagesize).exec()
  let arr = await brandModel.find({is_del:0}).exec()
  let total = arr.length
  res.send({
    data, total
  })
})



// 上传品牌图片
router.post('/upload', (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = 'upload'
  form.parse(req, (err, formData, imgData) => {
    res.send(imgData.file[0].path)
  })
})

// 添加品牌
router.post('/brand',async(req, res) => {
  let body = req.body;
  let data = brandModel.create(body)
  console.log(data);
  res.send(data)
})

// 将品牌添加至回收站
router.patch('/changeState/:id', async(req, res) => {
  let _id = req.params.id
  let is_del = req.body.is_del
  await brandModel.updateOne({_id}, {is_del})
  res.send({msg:'成功！'})
})

// 修改品牌
router.patch('/editbrand/:id', async(req, res) => {
  let _id = req.params.id
  let body = req.body
  let data = await brandModel.findOne({_id}).exec()
  if(data.brandimg != body.brandimg){
    fs.unlinkSync(data.brandimg)
  }
  let data2 = await brandModel.updateOne({_id}, {...body})
  res.send({'msg':'修改成功！', data2})
})

// 删除品牌
router.delete('/delBrand/:id', async (req, res) => {
  let _id = req.params.id
  console.log(_id);
  await brandModel.deleteOne({_id})
  res.send({status: 204})
})



// 商品分类属性




// 商品分类模块功能  // 无分页走if   有分页走else
router.get('/cate', async (req, res) => {
  let query = req.query
  let page = parseInt(query.page)
  let pagesize = parseInt(query.pagesize)
  let data = await catgoryModel.find({cate_level:0}).exec()
  let subdata = await catgoryModel.find({cate_level:1}).exec()
  let sundata = await catgoryModel.find({cate_level: 2}).exec()

  subdata.forEach(item => {
    item._doc.children = []
    sundata.forEach(subitem => {
      if(subitem.cate_pid == item._id){
        item._doc.children.push(subitem)
      }
    })
    if (!item._doc.children.length) delete item._doc.children
  })
  data.forEach(item => {
    item._doc.children = []
    subdata.forEach(subitem => {
      if (subitem.cate_pid == item._id){
        item._doc.children.push(subitem)
      }
    })
    if (!item._doc.children.length) delete item._doc.children
  })
  if (!page && !pagesize){
    data.forEach(item => {
      if (item._doc.children){
        item._doc.children.forEach(subitem =>{
          delete subitem._doc.children
        })
      }
    })
    res.send(data)
  }
  else{
    let total = data.length
    data = data.filter((item, index) => index >= (page-1) * pagesize && index < page * pagesize)
    res.send({data,total})
  }
})

// 添加分类
router.post('/cate',async (req, res) => {
  let body = req.body
  let data = await catgoryModel.create(body)
  res.send(data)
})

// 修改分类名称
router.patch('/cate/:id', async (req, res) => {
  let _id = req.params.id
  let body = req.body
  console.log(_id, body);
  await catgoryModel.updateOne({_id},body)
  res.send({msg:'修改成功!'})
})

// 删除分类
router.delete('/cate/:id', async( req , res ) => {
  // 获取参数_id
  let _id = req.params.id
  // 先进行查询
  let data = await catgoryModel.findOne({_id}).exec()
  // 然后判断_id对应的数据是一级,二级还是三级分类
  if (data.cate_level === 0){
    // 一级的话查找父级id为_id的二级分类
    let subdata = await catgoryModel.find({cate_pid: _id}).exec()
    // 如果有二级分类的话,循环二级分类,然后根据cate_pid删除三级分类
    if (subdata.length){
      subdata.forEach(async item => {
        await catgoryModel.deleteMany({cate_pid : item._id})
      })
    }
    // 最后再根据cate_pid删除二级分类
    await catgoryModel.deleteMany({cate_pid:_id})
    // 最后根据_id删除一级分类
    await catgoryModel.deleteOne({_id})
  }
  // 如果为二级分类的话
  else if(data.cate_level === 1){
    // 根据_id删除二级分类
    await catgoryModel.deleteOne({_id})
    // 根据cate_pid删除三级分类
    await catgoryModel.deleteMany({cate_pid:_id})
  }
  // 否则为三级分类
  else{
    // 根据_id删除三级分类
    await catgoryModel.deleteOne({_id})
  }
  res.send({msg:'删除成功!'})
})




// 商品接口

// 商品展示
router.get('/good', async (req, res) => {
  let pagesize = parseInt(req.query.pagesize) || 2
  let page = parseInt(req.query.page) || 1
  let search = req.query.search || ''
  let data = ''
  let total = 0
  if (search){
    let reg = RegExp(search)
    data = await goodsModel.find({goods_name:reg}).limit(pagesize).skip((page-1) * pagesize).populate('cate_id').populate('brand_id').exec()
    let count = await goodsModel.find({goods_name: reg}).exec()
    total = count.length
  }else{
    data = await goodsModel.find().limit(pagesize).skip((page-1) * pagesize).populate('cate_id').populate('brand_id').exec()
    total = await goodsModel.count()
  }
  res.send({data, total})
})

// 获取商品分类 作商品添加
router.get('/good/cate', async (req, res) => {
  let data = await catgoryModel.find({cate_level:0}).exec()
  let subdata = await catgoryModel.find({cate_level:1}).exec()
  let sundata = await catgoryModel.find({cate_level: 2}).exec()

  subdata.forEach(item => {
    item._doc.children = []
    sundata.forEach(subitem => {
      if(subitem.cate_pid == item._id){
        item._doc.children.push(subitem)
      }
    })
  })
  data.forEach(item => {
    item._doc.children = []
    subdata.forEach(subitem => {
      if (subitem.cate_pid == item._id){
        item._doc.children.push(subitem)
      }
    })
  })
  res.send(data)
})


// 添加商品
router.post('/good', async (req, res) => {
  let body = req.body
  let data = await goodsModel.create(body)
  res.send(data)
})

// 删除商品
router.delete('/delgood/:id', async(req, res) => {
  let _id = req.params.id
  await goodsModel.deleteOne({_id})
  res.send({status: 204})
})

// 修改商品
router.patch('/editgood/:id', async (req, res) => {
  let _id = req.params.id
  let body = req.body
  let data = await goodsModel.findOne({_id}).exec()
  if(data.goods_small_logo != body.goods_small_logo){
    fs.unlinkSync(data.goods_small_logo)
  }
  await goodsModel.updateOne({_id}, body)
  res.send({status: 201})
})


// 订单管理

// 获取订单列表

router.get('/order/:id', async (req, res) => {
  let user_id = req.params.id
  let page = parseInt(req.query.page) || 1
  let pagesize = parseInt(req.query.pagesize) || 2
  let search = req.query.search
  let data = []
  let total = 0
  if (search){
    // let reg = RegExp(search)
    data = await orderModel.find({$and : [{user_id}, {order_number: search}]}).limit(pagesize).skip((page-1) * pagesize).exec()
    let count = await orderModel.find({$and : [{user_id}, {order_number: search}]}).exec()
    total = count.length
  }else{
    data = await orderModel.find({user_id}).limit(pagesize).skip((page-1) * pagesize).exec()
    let count = await orderModel.find({user_id}).exec()
    total = count.length
  }
  console.log(data, total);
  res.send({data, total, status: 200})
})

// 添加订单
router.post('/order/:id', async (req, res) => {
  let user_id = req.params.id
  let body = req.body
  let data = await orderModel.create({user_id, ...body})
  res.send(data)
})

// 修改订单地址
router.patch('/order/:id', async(req, res) => {
  let _id = req.params.id
  let body = req.body
  await orderModel.updateOne({_id}, body)
  res.send({status: 201})
})


module.exports = router;